package ai_bloomfilter

import (
	"fmt"
	"github.com/spf13/viper"


	"ai_router"
	"ai_util"
	"ai_redis"
)


var wsentinel *ai_redis.AISentinel
var wbloomfilter *AIBloomFilter
var whandler *AIHandler
var wroute *ai_router.AIRoute

func Init(configfile string) error {
	confdir, confbase, conftype, err := ai_util.ParseConfigPath(configfile)
	if err != nil {
		return err
	}

	config := viper.New()
	{
		config.AddConfigPath(confdir)
		config.SetConfigName(confbase)
		config.SetConfigType(conftype)
		if err := config.ReadInConfig(); err != nil {
			return err
		}
		for key, val := range config.AllSettings() {
			fmt.Printf("%v: %v\n", key, val)
		}
	}

	{
		wsentinel = &ai_redis.AISentinel{}
		err := wsentinel.Init(config.GetString("sentinel.master"), config.GetStringSlice("sentinel.address"),
			config.GetString("sentinel.password"), config.GetInt("sentinel.db"))
		if err != nil {
			return err
		}
	}

	{
		wbloomfilter = &AIBloomFilter{}
		err := wbloomfilter.Init(config.GetInt("bloomfilter.capacity"), config.GetFloat64("bloomfilter.error_rate"),
			wsentinel, config.GetString("bloomfilter.key"))
		if err != nil {
			return err
		}
	}

	{
		whandler = &AIHandler{}
		if err := whandler.Init(wbloomfilter); err != nil {
			return err
		}
	}

	{
		wroute = &ai_router.AIRoute{}
		if err := wroute.Init(config.GetString("bloomfilter.address")); err != nil {
			return err
		}
		wroute.SetGetHandler("/filter", whandler.Handler)
		// wroute.SetPostHandler("/filter", whandler.Handler)
	}
	return nil
}

func Run() {
	go wroute.Run()
}